/************************************************************************************************
 * test examples of 100 interesting program in C
 * test 068.c
 * 9 digits accumulatable division number
 * which is: number[0~i] % i == 0 (i <= 9)
 ***********************************************************************************************/

#include <stdio.h>
#include <string.h>

/*
 *
 */

#define DIGITS 8

int printNumber(int* a)
{
	int i = 0;
	for (i = 0; i < DIGITS; i++)
		printf("%d", a[i]);
	printf("\n");
}

int main()
{
	int number[DIGITS];
	int used[DIGITS];

	int i = 0;
	for (i = 0; i < DIGITS; i++)
	{
		number[i] = 0;
		used[i] = 0;
	}

	int p = 0;
	int fin = 0;
	while(1)
	{
		while (fin == 0 && p < DIGITS)
		{
			// printf("Now testing %d digit of ", p+1);
			// printNumber(number);
			if (number[p] >= DIGITS)
				if (p == 0)
					fin = 1;
				else
				{
					if (number[p] == DIGITS)
					{
						used[number[p]-1] = 0;
						// printf("**%d is released and backtrace\n", number[p]);
					}
					number[p--] = 0;
				}
			else
			{
				if (number[p] != 0)
				{
					used[number[p]-1] = 0;
					// printf("**%d is released\n", number[p]);
				}
				number[p]++;
				for (; number[p] <= DIGITS; number[p]++)
				{
					if (used[number[p]-1] == 1) continue;
					int accum = 0, j = 0;
					for (j = 0; j <= p; j++)
						accum = accum*10 + number[j];
					// printf("--%d mod %d = 0\n", accum, p+1);
					if (accum % (p+1) == 0)
					{
						used[number[p]-1] = 1;
						// printf("**%d is used\n", number[p]);
						p++;
						// flag = 1;
						break;
					}
				}
				// printNumber(number);
			}
		}
		if (fin == 1) break;
		else {
			int k = 0;
			char hint[] = "Find a proper number: ";
			for (k = 0; k < strlen(hint)+DIGITS; k++) printf("-");
			printf("\n");
			printf("%s", hint);
			printNumber(number);
			for (k = 0; k < strlen(hint)+DIGITS; k++) printf("-");
			printf("\n");
			p--;
		}
	}			
}

